'''
Created on Jan 23, 2015

@author: Alex

From quantstart.com
'''

import pandas as pd
import urllib

def construct_futures_symbols(symbol, start_year=2010, end_year=2014):
    """
    Construct a list of futures contract codes for a
    particular symbol and timeframe.
    """
    futures = []
    months = 'HMUZ' #March, June, September, December delivery codes
    
    for y in range(start_year, end_year+1):
        for m in months:
            futures.append("{}{}{}".format(symbol, m, y))
    
    return futures

def download_contract_from_quandl(exchange, contract, auth_token, dl_dir):
    """
    Download an individual futures contract from Quandl and then 
    store it to disk in the 'dl_dir' directory. An auth_token is required,
    which is obtained from the Quandl upon sign-up.
    """
    
    #Construct the API call from the contract and auth_token
    
    api_call_head = "https://www.quandl.com/api/v1/datasets/{}/{}.csv".format(exchange, contract)
    
    params = "?&auth_token={}&sort_order=asc".format(auth_token)
    
    data = urllib.request.urlopen("{}{}".format(api_call_head, params)).read()
    
    fc = open('\{}\{}.csv'.format(dl_dir, contract), 'w')
    fc.write(data.decode('utf-8'))
    fc.close()
    
def download_historical_contracts(exchange, symbol, auth_token, dl_dir, 
                                  start_year=2010, end_year=2014):
    """
    Download all futures contracts for a specified exchange and symbol between
    a start_ear and an end_year.
    """
    
    contracts = construct_futures_symbols(symbol, start_year, end_year)
    
    for c in contracts:
        download_contract_from_quandl(exchange, c, auth_token, dl_dir)

auth_token = 'CZ1z-XF_oNi5sSSSRRpx'
dl_dir = 'Users\Alex\Desktop\Data\Quandl\Futures\ES'
exchange = 'CME'
symbol = 'ES'
start_year = 2014
end_year = 2014

download_historical_contracts(exchange, symbol, auth_token, dl_dir, 
                              start_year, end_year)
